home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume22 / gawk2.11 / part04 < prev    next >
Encoding:
Internet Message Format  |  1990-06-07  |  54.5 KB

  1. Subject:  v22i090:  GNU AWK, version 2.11, Part04/16
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: 35836423 9d91dc22 c899fe92 c7b41f10
  5.  
  6. Submitted-by: "Arnold D. Robbins" <arnold@unix.cc.emory.edu>
  7. Posting-number: Volume 22, Issue 90
  8. Archive-name: gawk2.11/part04
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  ./gawk.texinfo.05 ./patchlevel.h ./pc.d/popen.c
  17. # Wrapped by rsalz@litchi.bbn.com on Wed Jun  6 12:24:48 1990
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. echo If this archive is complete, you will see the following message:
  20. echo '          "shar: End of archive 4 (of 16)."'
  21. if test -f './gawk.texinfo.05' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'./gawk.texinfo.05'\"
  23. else
  24.   echo shar: Extracting \"'./gawk.texinfo.05'\" \(49666 characters\)
  25.   sed "s/^X//" >'./gawk.texinfo.05' <<'END_OF_FILE'
  26. XIf a line number is repeated, the last line with a given number overrides
  27. Xthe others.
  28. X
  29. XGaps in the line numbers can be handled with an easy improvement to the
  30. Xprogram's @code{END} rule:
  31. X
  32. X@example
  33. XEND @{
  34. X  for (x = 1; x <= max; x++)
  35. X    if (x in arr)
  36. X      print arr[x]
  37. X@}
  38. X@end example
  39. X
  40. X@node Scanning an Array, Delete, Array Example, Arrays
  41. X@section Scanning All Elements of an Array
  42. X@cindex @code{for (x in @dots{})}
  43. X@cindex arrays, special @code{for} statement
  44. X@cindex scanning an array
  45. X
  46. XIn programs that use arrays, often you need a loop that executes
  47. Xonce for each element of an array.  In other languages, where arrays are
  48. Xcontiguous and indices are limited to positive integers, this is
  49. Xeasy: the largest index is one less than the length of the array, and you can
  50. Xfind all the valid indices by counting from zero up to that value.  This
  51. Xtechnique won't do the job in @code{awk}, since any number or string
  52. Xmay be an array index.  So @code{awk} has a special kind of @code{for}
  53. Xstatement for scanning an array:
  54. X
  55. X@example
  56. Xfor (@var{var} in @var{array})
  57. X  @var{body}
  58. X@end example
  59. X
  60. X@noindent
  61. XThis loop executes @var{body} once for each different value that your
  62. Xprogram has previously used as an index in @var{array}, with the
  63. Xvariable @var{var} set to that index.@refill
  64. X
  65. XHere is a program that uses this form of the @code{for} statement.  The
  66. Xfirst rule scans the input records and notes which words appear (at
  67. Xleast once) in the input, by storing a 1 into the array @code{used} with
  68. Xthe word as index.  The second rule scans the elements of @code{used} to
  69. Xfind all the distinct words that appear in the input.  It prints each
  70. Xword that is more than 10 characters long, and also prints the number of
  71. Xsuch words.  @xref{Built-in}, for more information on the built-in
  72. Xfunction @code{length}.
  73. X
  74. X@example
  75. X# Record a 1 for each word that is used at least once.
  76. X@{
  77. X  for (i = 0; i < NF; i++)
  78. X    used[$i] = 1
  79. X@}
  80. X
  81. X# Find number of distinct words more than 10 characters long.
  82. XEND @{
  83. X  num_long_words = 0
  84. X  for (x in used)
  85. X    if (length(x) > 10) @{
  86. X      ++num_long_words
  87. X      print x
  88. X  @}
  89. X  print num_long_words, "words longer than 10 characters"
  90. X@}
  91. X@end example
  92. X
  93. X@noindent
  94. X@xref{Sample Program}, for a more detailed example of this type.
  95. X
  96. XThe order in which elements of the array are accessed by this statement
  97. Xis determined by the internal arrangement of the array elements within
  98. X@code{awk} and cannot be controlled or changed.  This can lead to
  99. Xproblems if new elements are added to @var{array} by statements in
  100. X@var{body}; you cannot predict whether or not the @code{for} loop will
  101. Xreach them.  Similarly, changing @var{var} inside the loop can produce
  102. Xstrange results.  It is best to avoid such things.@refill
  103. X
  104. X@node Delete, Multi-dimensional, Scanning an Array, Arrays
  105. X@section The @code{delete} Statement
  106. X@cindex @code{delete} statement
  107. X@cindex deleting elements of arrays
  108. X@cindex removing elements of arrays
  109. X@cindex arrays, deleting an element
  110. X
  111. XYou can remove an individual element of an array using the @code{delete}
  112. Xstatement:
  113. X
  114. X@example
  115. Xdelete @var{array}[@var{index}]
  116. X@end example
  117. X
  118. XWhen an array element is deleted, it is as if you had never referred to it
  119. Xand had never given it any value.  Any value the element formerly had
  120. Xcan no longer be obtained.
  121. X
  122. XHere is an example of deleting elements in an array:
  123. X
  124. X@example
  125. Xfor (i in frequencies)
  126. X  delete frequencies[i]
  127. X@end example
  128. X
  129. X@noindent
  130. XThis example removes all the elements from the array @code{frequencies}.
  131. X
  132. XIf you delete an element, a subsequent @code{for} statement to scan the array
  133. Xwill not report that element, and the @code{in} operator to check for
  134. Xthe presence of that element will return 0:
  135. X
  136. X@example
  137. Xdelete foo[4]
  138. Xif (4 in foo)
  139. X  print "This will never be printed"
  140. X@end example
  141. X
  142. X@node Multi-dimensional, Multi-scanning, Delete, Arrays
  143. X@section Multi-dimensional Arrays
  144. X
  145. X@cindex subscripts, multi-dimensional in arrays
  146. X@cindex arrays, multi-dimensional subscripts
  147. X@cindex multi-dimensional subscripts
  148. XA multi-dimensional array is an array in which an element is identified
  149. Xby a sequence of indices, not a single index.  For example, a
  150. Xtwo-dimensional array requires two indices.  The usual way (in most
  151. Xlanguages, including @code{awk}) to refer to an element of a
  152. Xtwo-dimensional array named @code{grid} is with
  153. X@code{grid[@var{x},@var{y}]}.
  154. X
  155. X@vindex SUBSEP
  156. XMulti-dimensional arrays are supported in @code{awk} through
  157. Xconcatenation of indices into one string.  What happens is that
  158. X@code{awk} converts the indices into strings (@pxref{Conversion}) and
  159. Xconcatenates them together, with a separator between them.  This creates
  160. Xa single string that describes the values of the separate indices.  The
  161. Xcombined string is used as a single index into an ordinary,
  162. Xone-dimensional array.  The separator used is the value of the built-in
  163. Xvariable @code{SUBSEP}.
  164. X
  165. XFor example, suppose we evaluate the expression @code{foo[5,12]="value"}
  166. Xwhen the value of @code{SUBSEP} is @code{"@@"}.  The numbers 5 and 12 are
  167. Xconcatenated with a comma between them, yielding @code{"5@@12"}; thus,
  168. Xthe array element @code{foo["5@@12"]} is set to @code{"value"}.
  169. X
  170. XOnce the element's value is stored, @code{awk} has no record of whether
  171. Xit was stored with a single index or a sequence of indices.  The two
  172. Xexpressions @code{foo[5,12]} and @w{@code{foo[5 SUBSEP 12]}} always have
  173. Xthe same value.
  174. X
  175. XThe default value of @code{SUBSEP} is actually the string @code{"\034"},
  176. Xwhich contains a nonprinting character that is unlikely to appear in an
  177. X@code{awk} program or in the input data.
  178. X
  179. XThe usefulness of choosing an unlikely character comes from the fact
  180. Xthat index values that contain a string matching @code{SUBSEP} lead to
  181. Xcombined strings that are ambiguous.  Suppose that @code{SUBSEP} were
  182. X@code{"@@"}; then @w{@code{foo["a@@b", "c"]}} and @w{@code{foo["a",
  183. X"b@@c"]}} would be indistinguishable because both would actually be
  184. Xstored as @code{foo["a@@b@@c"]}.  Because @code{SUBSEP} is
  185. X@code{"\034"}, such confusion can actually happen only when an index
  186. Xcontains the character with ASCII code 034, which is a rare
  187. Xevent.@refill
  188. X
  189. XYou can test whether a particular index-sequence exists in a
  190. X``multi-dimensional'' array with the same operator @code{in} used for single
  191. Xdimensional arrays.  Instead of a single index as the left-hand operand,
  192. Xwrite the whole sequence of indices, separated by commas, in
  193. Xparentheses:@refill
  194. X
  195. X@example
  196. X(@var{subscript1}, @var{subscript2}, @dots{}) in @var{array}
  197. X@end example
  198. X
  199. XThe following example treats its input as a two-dimensional array of
  200. Xfields; it rotates this array 90 degrees clockwise and prints the
  201. Xresult.  It assumes that all lines have the same number of
  202. Xelements.
  203. X
  204. X@example
  205. Xawk '@{
  206. X     if (max_nf < NF)
  207. X          max_nf = NF
  208. X     max_nr = NR
  209. X     for (x = 1; x <= NF; x++)
  210. X          vector[x, NR] = $x
  211. X@}
  212. X
  213. XEND @{
  214. X     for (x = 1; x <= max_nf; x++) @{
  215. X          for (y = max_nr; y >= 1; --y)
  216. X               printf("%s ", vector[x, y])
  217. X          printf("\n")
  218. X     @}
  219. X@}'
  220. X@end example
  221. X
  222. X@noindent
  223. XWhen given the input:
  224. X
  225. X@example
  226. X1 2 3 4 5 6
  227. X2 3 4 5 6 1
  228. X3 4 5 6 1 2
  229. X4 5 6 1 2 3
  230. X@end example
  231. X
  232. X@noindent
  233. Xit produces:
  234. X
  235. X@example
  236. X4 3 2 1
  237. X5 4 3 2
  238. X6 5 4 3
  239. X1 6 5 4
  240. X2 1 6 5
  241. X3 2 1 6
  242. X@end example
  243. X
  244. X@node Multi-scanning, , Multi-dimensional, Arrays
  245. X@section Scanning Multi-dimensional Arrays
  246. X
  247. XThere is no special @code{for} statement for scanning a
  248. X``multi-dimensional'' array; there cannot be one, because in truth there
  249. Xare no multi-dimensional arrays or elements; there is only a
  250. Xmulti-dimensional @emph{way of accessing} an array.
  251. X
  252. XHowever, if your program has an array that is always accessed as
  253. Xmulti-dimensional, you can get the effect of scanning it by combining
  254. Xthe scanning @code{for} statement (@pxref{Scanning an Array}) with the
  255. X@code{split} built-in function (@pxref{String Functions}).  It works
  256. Xlike this:
  257. X
  258. X@example
  259. Xfor (combined in @var{array}) @{
  260. X  split(combined, separate, SUBSEP)
  261. X  @dots{}
  262. X@}
  263. X@end example
  264. X
  265. X@noindent
  266. XThis finds each concatenated, combined index in the array, and splits it
  267. Xinto the individual indices by breaking it apart where the value of
  268. X@code{SUBSEP} appears.  The split-out indices become the elements of
  269. Xthe array @code{separate}.
  270. X
  271. XThus, suppose you have previously stored in @code{@var{array}[1,
  272. X"foo"]}; then an element with index @code{"1\034foo"} exists in
  273. X@var{array}.  (Recall that the default value of @code{SUBSEP} contains
  274. Xthe character with code 034.)  Sooner or later the @code{for} statement
  275. Xwill find that index and do an iteration with @code{combined} set to
  276. X@code{"1\034foo"}.  Then the @code{split} function is called as
  277. Xfollows:
  278. X
  279. X@example
  280. Xsplit("1\034foo", separate, "\034")
  281. X@end example
  282. X
  283. X@noindent
  284. XThe result of this is to set @code{separate[1]} to 1 and @code{separate[2]}
  285. Xto @code{"foo"}.  Presto, the original sequence of separate indices has
  286. Xbeen recovered.
  287. X
  288. X@node Built-in, User-defined, Arrays, Top
  289. X@chapter Built-in Functions
  290. X
  291. X@cindex built-in functions
  292. X@dfn{Built-in} functions are functions that are always available for
  293. Xyour @code{awk} program to call.  This chapter defines all the built-in
  294. Xfunctions in @code{awk}; some of them are mentioned in other sections,
  295. Xbut they are summarized here for your convenience.  (You can also define
  296. Xnew functions yourself.  @xref{User-defined}.)
  297. X
  298. X@menu
  299. X* Calling Built-in::   How to call built-in functions.
  300. X
  301. X* Numeric Functions::  Functions that work with numbers,
  302. X                       including @code{int}, @code{sin} and @code{rand}.
  303. X
  304. X* String Functions::   Functions for string manipulation,
  305. X                       such as @code{split}, @code{match}, and @code{sprintf}.
  306. X
  307. X* I/O Functions::      Functions for files and shell commands
  308. X@end menu
  309. X
  310. X@node Calling Built-in, Numeric Functions, Built-in, Built-in
  311. X@section Calling Built-in Functions
  312. X
  313. XTo call a built-in function, write the name of the function followed
  314. Xby arguments in parentheses.  For example, @code{atan2(y + z, 1)}
  315. Xis a call to the function @code{atan2}, with two arguments.
  316. X
  317. XWhitespace is ignored between the built-in function name and the
  318. Xopen-parenthesis, but we recommend that you avoid using whitespace
  319. Xthere.  User-defined functions do not permit whitespace in this way, and
  320. Xyou will find it easier to avoid mistakes by following a simple
  321. Xconvention which always works: no whitespace after a function name.
  322. X
  323. XEach built-in function accepts a certain number of arguments.  In most
  324. Xcases, any extra arguments given to built-in functions are ignored.  The
  325. Xdefaults for omitted arguments vary from function to function and are
  326. Xdescribed under the individual functions.
  327. X
  328. XWhen a function is called, expressions that create the function's actual
  329. Xparameters are evaluated completely before the function call is performed.
  330. XFor example, in the code fragment:
  331. X
  332. X@example
  333. Xi = 4
  334. Xj = sqrt(i++)
  335. X@end example
  336. X
  337. X@noindent
  338. Xthe variable @code{i} is set to 5 before @code{sqrt} is called
  339. Xwith a value of 4 for its actual parameter.
  340. X
  341. X@node Numeric Functions, String Functions, Calling Built-in, Built-in
  342. X@section Numeric Built-in Functions
  343. X
  344. XHere is a full list of built-in functions that work with numbers:
  345. X
  346. X@table @code
  347. X@item int(@var{x})
  348. XThis gives you the integer part of @var{x}, truncated toward 0.  This
  349. Xproduces the nearest integer to @var{x}, located between @var{x} and 0.
  350. X
  351. XFor example, @code{int(3)} is 3, @code{int(3.9)} is 3, @code{int(-3.9)}
  352. Xis @minus{}3, and @code{int(-3)} is @minus{}3 as well.@refill
  353. X
  354. X@item sqrt(@var{x})
  355. XThis gives you the positive square root of @var{x}.  It reports an error
  356. Xif @var{x} is negative.  Thus, @code{sqrt(4)} is 2.@refill
  357. X
  358. X@item exp(@var{x})
  359. XThis gives you the exponential of @var{x}, or reports an error if
  360. X@var{x} is out of range.  The range of values @var{x} can have depends
  361. Xon your machine's floating point representation.@refill
  362. X
  363. X@item log(@var{x})
  364. XThis gives you the natural logarithm of @var{x}, if @var{x} is positive;
  365. Xotherwise, it reports an error.@refill
  366. X
  367. X@item sin(@var{x})
  368. XThis gives you the sine of @var{x}, with @var{x} in radians.
  369. X
  370. X@item cos(@var{x})
  371. XThis gives you the cosine of @var{x}, with @var{x} in radians.
  372. X
  373. X@item atan2(@var{y}, @var{x})
  374. XThis gives you the arctangent of @code{@var{y} / @var{x}}, with the
  375. Xquotient understood in radians.
  376. X
  377. X@item rand()
  378. XThis gives you a random number.  The values of @code{rand} are
  379. Xuniformly-distributed between 0 and 1.  The value is never 0 and never
  380. X1.
  381. X
  382. XOften you want random integers instead.  Here is a user-defined function
  383. Xyou can use to obtain a random nonnegative integer less than @var{n}:
  384. X
  385. X@example
  386. Xfunction randint(n) @{
  387. X     return int(n * rand())
  388. X@}
  389. X@end example
  390. X
  391. X@noindent
  392. XThe multiplication produces a random real number greater than 0 and less
  393. Xthan @var{n}.  We then make it an integer (using @code{int}) between 0
  394. Xand @code{@var{n} @minus{} 1}.
  395. X
  396. XHere is an example where a similar function is used to produce
  397. Xrandom integers between 1 and @var{n}:
  398. X
  399. X@example
  400. Xawk '
  401. X# Function to roll a simulated die.
  402. Xfunction roll(n) @{ return 1 + int(rand() * n) @}
  403. X
  404. X# Roll 3 six-sided dice and print total number of points.
  405. X@{
  406. X      printf("%d points\n", roll(6)+roll(6)+roll(6))
  407. X@}'
  408. X@end example
  409. X
  410. X@strong{Note:} @code{rand} starts generating numbers from the same
  411. Xpoint, or @dfn{seed}, each time you run @code{awk}.  This means that
  412. Xa program will produce the same results each time you run it.
  413. XThe numbers are random within one @code{awk} run, but predictable
  414. Xfrom run to run.  This is convenient for debugging, but if you want
  415. Xa program to do different things each time it is used, you must change
  416. Xthe seed to a value that will be different in each run.  To do this,
  417. Xuse @code{srand}.
  418. X
  419. X@item srand(@var{x})
  420. XThe function @code{srand} sets the starting point, or @dfn{seed},
  421. Xfor generating random numbers to the value @var{x}.
  422. X
  423. XEach seed value leads to a particular sequence of ``random'' numbers.
  424. XThus, if you set the seed to the same value a second time, you will get
  425. Xthe same sequence of ``random'' numbers again.
  426. X
  427. XIf you omit the argument @var{x}, as in @code{srand()}, then the current
  428. Xdate and time of day are used for a seed.  This is the way to get random
  429. Xnumbers that are truly unpredictable.
  430. X
  431. XThe return value of @code{srand} is the previous seed.  This makes it
  432. Xeasy to keep track of the seeds for use in consistently reproducing
  433. Xsequences of random numbers.
  434. X@end table
  435. X
  436. X@node String Functions, I/O Functions, Numeric Functions, Built-in
  437. X@section Built-in Functions for String Manipulation
  438. X
  439. X  The functions in this section look at the text of one or more
  440. Xstrings.
  441. X
  442. X@table @code
  443. X@item index(@var{in}, @var{find})
  444. X@findex match
  445. XThis searches the string @var{in} for the first occurrence of the string
  446. X@var{find}, and returns the position where that occurrence begins in the
  447. Xstring @var{in}.  For example:@refill
  448. X
  449. X@example
  450. Xawk 'BEGIN @{ print index("peanut", "an") @}'
  451. X@end example
  452. X
  453. X@noindent
  454. Xprints @samp{3}.  If @var{find} is not found, @code{index} returns 0.
  455. X
  456. X@item length(@var{string})
  457. X@findex length
  458. XThis gives you the number of characters in @var{string}.  If
  459. X@var{string} is a number, the length of the digit string representing
  460. Xthat number is returned.  For example, @code{length("abcde")} is 5.  By
  461. Xcontrast, @code{length(15 * 35)} works out to 3.  How?  Well, 15 * 35 =
  462. X525, and 525 is then converted to the string @samp{"525"}, which has
  463. Xthree characters.
  464. X
  465. XIf no argument is supplied, @code{length} returns the length of @code{$0}.
  466. X
  467. X@item match(@var{string}, @var{regexp})
  468. X@findex match
  469. XThe @code{match} function searches the string, @var{string}, for the
  470. Xlongest, leftmost substring matched by the regular expression,
  471. X@var{regexp}.  It returns the character position, or @dfn{index}, of
  472. Xwhere that substring begins (1, if it starts at the beginning of
  473. X@var{string}).  If no match if found, it returns 0.
  474. X
  475. X@vindex RSTART
  476. X@vindex RLENGTH
  477. XThe @code{match} function sets the built-in variable @code{RSTART} to
  478. Xthe index.  It also sets the built-in variable @code{RLENGTH} to the
  479. Xlength of the matched substring.  If no match is found, @code{RSTART}
  480. Xis set to 0, and @code{RLENGTH} to @minus{}1.
  481. X
  482. XFor example:
  483. X
  484. X@example
  485. Xawk '@{
  486. X       if ($1 == "FIND")
  487. X         regex = $2
  488. X       else @{
  489. X         where = match($0, regex)
  490. X         if (where)
  491. X           print "Match of", regex, "found at", where, "in", $0
  492. X       @}
  493. X@}'
  494. X@end example
  495. X
  496. X@noindent
  497. XThis program looks for lines that match the regular expression stored in
  498. Xthe variable @code{regex}.  This regular expression can be changed.  If the
  499. Xfirst word on a line is @samp{FIND}, @code{regex} is changed to be the
  500. Xsecond word on that line.  Therefore, given:
  501. X
  502. X@example
  503. XFIND fo*bar
  504. XMy program was a foobar
  505. XBut none of it would doobar
  506. XFIND Melvin
  507. XJF+KM
  508. XThis line is property of The Reality Engineering Co.
  509. XThis file created by Melvin.
  510. X@end example
  511. X
  512. X@noindent
  513. X@code{awk} prints:
  514. X
  515. X@example
  516. XMatch of fo*bar found at 18 in My program was a foobar
  517. XMatch of Melvin found at 26 in This file created by Melvin.
  518. X@end example
  519. X
  520. X@item split(@var{string}, @var{array}, @var{fieldsep})
  521. X@findex split
  522. XThis divides @var{string} up into pieces separated by @var{fieldsep},
  523. Xand stores the pieces in @var{array}.  The first piece is stored in
  524. X@code{@var{array}[1]}, the second piece in @code{@var{array}[2]}, and so
  525. Xforth.  The string value of the third argument, @var{fieldsep}, is used
  526. Xas a regexp to search for to find the places to split @var{string}.  If
  527. Xthe @var{fieldsep} is omitted, the value of @code{FS} is used.
  528. X@code{split} returns the number of elements created.@refill
  529. X
  530. XThe @code{split} function, then, splits strings into pieces in a
  531. Xmanner similar to the way input lines are split into fields.  For example:
  532. X
  533. X@example
  534. Xsplit("auto-da-fe", a, "-")
  535. X@end example
  536. X
  537. X@noindent
  538. Xsplits the string @samp{auto-da-fe} into three fields using @samp{-} as the
  539. Xseparator.  It sets the contents of the array @code{a} as follows:
  540. X
  541. X@example
  542. Xa[1] = "auto"
  543. Xa[2] = "da"
  544. Xa[3] = "fe"
  545. X@end example
  546. X
  547. X@noindent
  548. XThe value returned by this call to @code{split} is 3.
  549. X
  550. X@item sprintf(@var{format}, @var{expression1},@dots{})
  551. X@findex sprintf
  552. XThis returns (without printing) the string that @code{printf} would
  553. Xhave printed out with the same arguments (@pxref{Printf}).  For
  554. Xexample:
  555. X
  556. X@example
  557. Xsprintf("pi = %.2f (approx.)", 22/7)
  558. X@end example
  559. X
  560. X@noindent
  561. Xreturns the string @w{@code{"pi = 3.14 (approx.)"}}.
  562. X
  563. X@item sub(@var{regexp}, @var{replacement}, @var{target})
  564. X@findex sub
  565. XThe @code{sub} function alters the value of @var{target}.
  566. XIt searches this value, which should be a string, for the
  567. Xleftmost substring matched by the regular expression, @var{regexp},
  568. Xextending this match as far as possible.  Then the entire string is
  569. Xchanged by replacing the matched text with @var{replacement}.
  570. XThe modified string becomes the new value of @var{target}.
  571. X
  572. XThis function is peculiar because @var{target} is not simply
  573. Xused to compute a value, and not just any expression will do: it
  574. Xmust be a variable, field or array reference, so that @code{sub} can
  575. Xstore a modified value there.  If this argument is omitted, then the
  576. Xdefault is to use and alter @code{$0}.
  577. X
  578. XFor example:@refill
  579. X
  580. X@example
  581. Xstr = "water, water, everywhere"
  582. Xsub(/at/, "ith", str)
  583. X@end example
  584. X
  585. X@noindent
  586. Xsets @code{str} to @w{@code{"wither, water, everywhere"}}, by replacing the
  587. Xleftmost, longest occurrence of @samp{at} with @samp{ith}.
  588. X
  589. XThe @code{sub} function returns the number of substitutions made (either
  590. Xone or zero).
  591. X
  592. XIf the special character @samp{&} appears in @var{replacement}, it
  593. Xstands for the precise substring that was matched by @var{regexp}.  (If
  594. Xthe regexp can match more than one string, then this precise substring
  595. Xmay vary.)  For example:@refill
  596. X
  597. X@example
  598. Xawk '@{ sub(/candidate/, "& and his wife"); print @}'
  599. X@end example
  600. X
  601. X@noindent
  602. Xchanges the first occurrence of @samp{candidate} to @samp{candidate
  603. Xand his wife} on each input line.
  604. X
  605. XThe effect of this special character can be turned off by putting a
  606. Xbackslash before it in the string.  As usual, to insert one backslash in
  607. Xthe string, you must write two backslashes.  Therefore, write @samp{\\&}
  608. Xin a string constant to include a literal @samp{&} in the replacement.
  609. XFor example, here is how to replace the first @samp{|} on each line with
  610. Xan @samp{&}:@refill
  611. X
  612. X@example
  613. Xawk '@{ sub(/\|/, "\\&"); print @}'
  614. X@end example
  615. X
  616. X@strong{Note:} as mentioned above, the third argument to @code{sub} must
  617. Xbe an lvalue.  Some versions of @code{awk} allow the third argument to
  618. Xbe an expression which is not an lvalue.  In such a case, @code{sub}
  619. Xwould still search for the pattern and return 0 or 1, but the result of
  620. Xthe substitution (if any) would be thrown away because there is no place
  621. Xto put it.  Such versions of @code{awk} accept expressions like
  622. Xthis:@refill
  623. X
  624. X@example
  625. Xsub(/USA/, "United States", "the USA and Canada")
  626. X@end example
  627. X
  628. X@noindent
  629. XBut that is considered erroneous in @code{gawk}.
  630. X
  631. X@item gsub(@var{regexp}, @var{replacement}, @var{target})
  632. X@findex gsub
  633. XThis is similar to the @code{sub} function, except @code{gsub} replaces
  634. X@emph{all} of the longest, leftmost, @emph{nonoverlapping} matching
  635. Xsubstrings it can find.  The @samp{g} in @code{gsub} stands for
  636. X``global'', which means replace everywhere.  For example:@refill
  637. X
  638. X@example
  639. Xawk '@{ gsub(/Britain/, "United Kingdom"); print @}'
  640. X@end example
  641. X
  642. X@noindent
  643. Xreplaces all occurrences of the string @samp{Britain} with @samp{United
  644. XKingdom} for all input records.@refill
  645. X
  646. XThe @code{gsub} function returns the number of substitutions made.  If
  647. Xthe variable to be searched and altered, @var{target}, is
  648. Xomitted, then the entire input record, @code{$0}, is used.@refill
  649. X
  650. XAs in @code{sub}, the characters @samp{&} and @samp{\} are special, and
  651. Xthe third argument must be an lvalue.
  652. X
  653. X@item substr(@var{string}, @var{start}, @var{length})
  654. X@findex substr
  655. XThis returns a @var{length}-character-long substring of @var{string},
  656. Xstarting at character number @var{start}.  The first character of a
  657. Xstring is character number one.  For example,
  658. X@code{substr("washington", 5, 3)} returns @code{"ing"}.@refill
  659. X
  660. XIf @var{length} is not present, this function returns the whole suffix of
  661. X@var{string} that begins at character number @var{start}.  For example,
  662. X@code{substr("washington", 5)} returns @code{"ington"}.
  663. X
  664. X@item tolower(@var{string})
  665. X@findex tolower
  666. XThis returns a copy of @var{string}, with each upper-case character
  667. Xin the string replaced with its corresponding lower-case character.
  668. XNonalphabetic characters are left unchanged.  For example,
  669. X@code{tolower("MiXeD cAsE 123")} returns @code{"mixed case 123"}.
  670. X
  671. X@item toupper(@var{string})
  672. X@findex toupper
  673. XThis returns a copy of @var{string}, with each lower-case character
  674. Xin the string replaced with its corresponding upper-case character.
  675. XNonalphabetic characters are left unchanged.  For example,
  676. X@code{toupper("MiXeD cAsE 123")} returns @code{"MIXED CASE 123"}.
  677. X@end table
  678. X
  679. X@node I/O Functions, , String Functions, Built-in
  680. X@section Built-in Functions For Input/Output
  681. X
  682. X@table @code
  683. X@item close(@var{filename})
  684. XClose the file @var{filename}, for input or output.  The argument may
  685. Xalternatively be a shell command that was used for redirecting to or
  686. Xfrom a pipe; then the pipe is closed.
  687. X
  688. X@xref{Close Input}, regarding closing input files and pipes.
  689. X@xref{Close Output}, regarding closing output files and pipes.
  690. X
  691. X@item system(@var{command})
  692. X@findex system
  693. X@cindex interaction of @code{awk} with other programs
  694. XThe system function allows the user to execute operating system commands
  695. Xand then return to the @code{awk} program.  The @code{system} function
  696. Xexecutes the command given by the string @var{command}.  It returns, as
  697. Xits value, the status returned by the command that was executed.
  698. X
  699. XFor example, if the following fragment of code is put in your @code{awk}
  700. Xprogram:
  701. X
  702. X@example
  703. XEND @{
  704. X     system("mail -s 'awk run done' operator < /dev/null")
  705. X@}
  706. X@end example
  707. X
  708. X@noindent
  709. Xthe system operator will be sent mail when the @code{awk} program
  710. Xfinishes processing input and begins its end-of-input processing.
  711. X
  712. XNote that much the same result can be obtained by redirecting
  713. X@code{print} or @code{printf} into a pipe.  However, if your @code{awk}
  714. Xprogram is interactive, @code{system} is useful for cranking up large
  715. Xself-contained programs, such as a shell or an editor.@refill
  716. X
  717. XSome operating systems cannot implement the @code{system} function.
  718. X@code{system} causes a fatal error if it is not supported.
  719. X@end table
  720. X
  721. X@node User-defined, Built-in Variables, Built-in, Top
  722. X@chapter User-defined Functions
  723. X
  724. X@cindex user-defined functions
  725. X@cindex functions, user-defined
  726. XComplicated @code{awk} programs can often be simplified by defining
  727. Xyour own functions.  User-defined functions can be called just like
  728. Xbuilt-in ones (@pxref{Function Calls}), but it is up to you to define
  729. Xthem---to tell @code{awk} what they should do.
  730. X
  731. X@menu
  732. X* Definition Syntax::   How to write definitions and what they mean.
  733. X* Function Example::    An example function definition and what it does.
  734. X* Function Caveats::    Things to watch out for.
  735. X* Return Statement::    Specifying the value a function returns.
  736. X@end menu
  737. X
  738. X@node Definition Syntax, Function Example, User-defined, User-defined
  739. X@section Syntax of Function Definitions
  740. X@cindex defining functions
  741. X@cindex function definition
  742. X
  743. XDefinitions of functions can appear anywhere between the rules of the
  744. X@code{awk} program.  Thus, the general form of an @code{awk} program is
  745. Xextended to include sequences of rules @emph{and} user-defined function
  746. Xdefinitions.
  747. X
  748. XThe definition of a function named @var{name} looks like this:
  749. X
  750. X@example
  751. Xfunction @var{name} (@var{parameter-list}) @{
  752. X     @var{body-of-function}
  753. X@}
  754. X@end example
  755. X
  756. X@noindent
  757. XThe keyword @code{function} may be abbreviated @code{func}.
  758. X
  759. X@var{name} is the name of the function to be defined.  A valid function
  760. Xname is like a valid variable name: a sequence of letters, digits and
  761. Xunderscores, not starting with a digit.
  762. X
  763. X@var{parameter-list} is a list of the function's arguments and local
  764. Xvariable names, separated by commas.  When the function is called,
  765. Xthe argument names are used to hold the argument values given in
  766. Xthe call.  The local variables are initialized to the null string.
  767. X
  768. XThe @var{body-of-function} consists of @code{awk} statements.  It is the
  769. Xmost important part of the definition, because it says what the function
  770. Xshould actually @emph{do}.  The argument names exist to give the body a
  771. Xway to talk about the arguments; local variables, to give the body
  772. Xplaces to keep temporary values.
  773. X
  774. XArgument names are not distinguished syntactically from local variable
  775. Xnames; instead, the number of arguments supplied when the function is
  776. Xcalled determines how many argument variables there are.  Thus, if three
  777. Xargument values are given, the first three names in @var{parameter-list}
  778. Xare arguments, and the rest are local variables.
  779. X
  780. XIt follows that if the number of arguments is not the same in all calls
  781. Xto the function, some of the names in @var{parameter-list} may be
  782. Xarguments on some occasions and local variables on others.  Another
  783. Xway to think of this is that omitted arguments default to the
  784. Xnull string.
  785. X
  786. XUsually when you write a function you know how many names you intend to
  787. Xuse for arguments and how many you intend to use as locals.  By
  788. Xconvention, you should write an extra space between the arguments and
  789. Xthe locals, so that other people can follow how your function is
  790. Xsupposed to be used.
  791. X
  792. XDuring execution of the function body, the arguments and local variable
  793. Xvalues hide or @dfn{shadow} any variables of the same names used in the
  794. Xrest of the program.  The shadowed variables are not accessible in the
  795. Xfunction definition, because there is no way to name them while their
  796. Xnames have been taken away for the local variables.  All other variables
  797. Xused in the @code{awk} program can be referenced or set normally in the
  798. Xfunction definition.
  799. X
  800. XThe arguments and local variables last only as long as the function body
  801. Xis executing.  Once the body finishes, the shadowed variables come back.
  802. X
  803. XThe function body can contain expressions which call functions.  They
  804. Xcan even call this function, either directly or by way of another
  805. Xfunction.  When this happens, we say the function is @dfn{recursive}.
  806. X
  807. XThere is no need in @code{awk} to put the definition of a function
  808. Xbefore all uses of the function.  This is because @code{awk} reads the
  809. Xentire program before starting to execute any of it.
  810. X
  811. X@node Function Example, Function Caveats, Definition Syntax, User-defined
  812. X@section Function Definition Example
  813. X
  814. XHere is an example of a user-defined function, called @code{myprint}, that
  815. Xtakes a number and prints it in a specific format.
  816. X
  817. X@example
  818. Xfunction myprint(num)
  819. X@{
  820. X     printf "%6.3g\n", num
  821. X@}
  822. X@end example
  823. X
  824. X@noindent
  825. XTo illustrate, here is an @code{awk} rule which uses our @code{myprint}
  826. Xfunction:
  827. X
  828. X@example
  829. X$3 > 0     @{ myprint($3) @}
  830. X@end example
  831. X
  832. X@noindent
  833. XThis program prints, in our special format, all the third fields that
  834. Xcontain a positive number in our input.  Therefore, when given:
  835. X
  836. X@example
  837. X 1.2   3.4   5.6   7.8
  838. X 9.10 11.12 13.14 15.16
  839. X17.18 19.20 21.22 23.24
  840. X@end example
  841. X
  842. X@noindent
  843. Xthis program, using our function to format the results, prints:
  844. X
  845. X@example
  846. X   5.6
  847. X  13.1
  848. X  21.2
  849. X@end example
  850. X
  851. XHere is a rather contrived example of a recursive function.  It prints a
  852. Xstring backwards:
  853. X
  854. X@example
  855. Xfunction rev (str, len) @{
  856. X    if (len == 0) @{
  857. X        printf "\n"
  858. X        return
  859. X    @}
  860. X    printf "%c", substr(str, len, 1)
  861. X    rev(str, len - 1)
  862. X@}
  863. X@end example
  864. X
  865. X@node Function Caveats, Return Statement, Function Example, User-defined
  866. X@section Calling User-defined Functions
  867. X
  868. X@dfn{Calling a function} means causing the function to run and do its job.
  869. XA function call is an expression, and its value is the value returned by
  870. Xthe function.
  871. X
  872. XA function call consists of the function name followed by the arguments
  873. Xin parentheses.  What you write in the call for the arguments are
  874. X@code{awk} expressions; each time the call is executed, these
  875. Xexpressions are evaluated, and the values are the actual arguments.  For
  876. Xexample, here is a call to @code{foo} with three arguments:
  877. X
  878. X@example
  879. Xfoo(x y, "lose", 4 * z)
  880. X@end example
  881. X
  882. X@strong{Note:} whitespace characters (spaces and tabs) are not allowed
  883. Xbetween the function name and the open-parenthesis of the argument list.
  884. XIf you write whitespace by mistake, @code{awk} might think that you mean
  885. Xto concatenate a variable with an expression in parentheses.  However, it
  886. Xnotices that you used a function name and not a variable name, and reports
  887. Xan error.
  888. X
  889. X@cindex call by value
  890. XWhen a function is called, it is given a @emph{copy} of the values of
  891. Xits arguments.  This is called @dfn{call by value}.  The caller may use
  892. Xa variable as the expression for the argument, but the called function
  893. Xdoes not know this: all it knows is what value the argument had.  For
  894. Xexample, if you write this code:
  895. X
  896. X@example
  897. Xfoo = "bar"
  898. Xz = myfunc(foo)
  899. X@end example
  900. X
  901. X@noindent
  902. Xthen you should not think of the argument to @code{myfunc} as being
  903. X``the variable @code{foo}''.  Instead, think of the argument as the
  904. Xstring value, @code{"bar"}.
  905. X
  906. XIf the function @code{myfunc} alters the values of its local variables,
  907. Xthis has no effect on any other variables.  In particular, if @code{myfunc}
  908. Xdoes this:
  909. X
  910. X@example
  911. Xfunction myfunc (win) @{
  912. X  print win
  913. X  win = "zzz"
  914. X  print win
  915. X@}
  916. X@end example
  917. X
  918. X@noindent
  919. Xto change its first argument variable @code{win}, this @emph{does not}
  920. Xchange the value of @code{foo} in the caller.  The role of @code{foo} in
  921. Xcalling @code{myfunc} ended when its value, @code{"bar"}, was computed.
  922. XIf @code{win} also exists outside of @code{myfunc}, the function body
  923. Xcannot alter this outer value, because it is shadowed during the
  924. Xexecution of @code{myfunc} and cannot be seen or changed from there.
  925. X
  926. X@cindex call by reference
  927. XHowever, when arrays are the parameters to functions, they are @emph{not}
  928. Xcopied.  Instead, the array itself is made available for direct manipulation
  929. Xby the function.  This is usually called @dfn{call by reference}.
  930. XChanges made to an array parameter inside the body of a function @emph{are}
  931. Xvisible outside that function.  @emph{This can be very dangerous if you don't
  932. Xwatch what you are doing.}  For example:@refill
  933. X
  934. X@example
  935. Xfunction changeit (array, ind, nvalue) @{
  936. X     array[ind] = nvalue
  937. X@}
  938. X
  939. XBEGIN @{
  940. X           a[1] = 1 ; a[2] = 2 ; a[3] = 3
  941. X           changeit(a, 2, "two")
  942. X           printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
  943. X      @}
  944. X@end example
  945. X
  946. X@noindent
  947. Xprints @samp{a[1] = 1, a[2] = two, a[3] = 3}, because calling
  948. X@code{changeit} stores @code{"two"} in the second element of @code{a}.
  949. X
  950. X@node Return Statement, , Function Caveats, User-defined
  951. X@section The @code{return} Statement
  952. X@cindex @code{return} statement
  953. X
  954. XThe body of a user-defined function can contain a @code{return} statement.
  955. XThis statement returns control to the rest of the @code{awk} program.  It
  956. Xcan also be used to return a value for use in the rest of the @code{awk}
  957. Xprogram.  It looks like this:@refill
  958. X
  959. X@example
  960. Xreturn @var{expression}
  961. X@end example
  962. X
  963. XThe @var{expression} part is optional.  If it is omitted, then the returned
  964. Xvalue is undefined and, therefore, unpredictable.
  965. X
  966. XA @code{return} statement with no value expression is assumed at the end of
  967. Xevery function definition.  So if control reaches the end of the function
  968. Xdefinition, then the function returns an unpredictable value.
  969. X
  970. XHere is an example of a user-defined function that returns a value
  971. Xfor the largest number among the elements of an array:@refill
  972. X
  973. X@example
  974. Xfunction maxelt (vec,   i, ret) @{
  975. X     for (i in vec) @{
  976. X          if (ret == "" || vec[i] > ret)
  977. X               ret = vec[i]
  978. X     @}
  979. X     return ret
  980. X@}
  981. X@end example
  982. X
  983. X@noindent
  984. XYou call @code{maxelt} with one argument, an array name.  The local
  985. Xvariables @code{i} and @code{ret} are not intended to be arguments;
  986. Xwhile there is nothing to stop you from passing two or three arguments
  987. Xto @code{maxelt}, the results would be strange.  The extra space before
  988. X@code{i} in the function parameter list is to indicate that @code{i} and
  989. X@code{ret} are not supposed to be arguments.  This is a convention which
  990. Xyou should follow when you define functions.
  991. X
  992. XHere is a program that uses our @code{maxelt} function.  It loads an
  993. Xarray, calls @code{maxelt}, and then reports the maximum number in that
  994. Xarray:@refill
  995. X
  996. X@example
  997. Xawk '
  998. Xfunction maxelt (vec,   i, ret) @{
  999. X     for (i in vec) @{
  1000. X          if (ret == "" || vec[i] > ret)
  1001. X               ret = vec[i]
  1002. X     @}
  1003. X     return ret
  1004. X@}
  1005. X
  1006. X# Load all fields of each record into nums.
  1007. X@{
  1008. X          for(i = 1; i <= NF; i++)
  1009. X               nums[NR, i] = $i
  1010. X@}
  1011. X
  1012. XEND @{
  1013. X     print maxelt(nums)
  1014. X@}'
  1015. X@end example
  1016. X
  1017. XGiven the following input:
  1018. X
  1019. X@example
  1020. X 1 5 23 8 16
  1021. X44 3 5 2 8 26
  1022. X256 291 1396 2962 100
  1023. X-6 467 998 1101
  1024. X99385 11 0 225
  1025. X@end example
  1026. X
  1027. X@noindent
  1028. Xour program tells us (predictably) that:
  1029. X
  1030. X@example
  1031. X99385
  1032. X@end example
  1033. X
  1034. X@noindent
  1035. Xis the largest number in our array.
  1036. X
  1037. X@node Built-in Variables, Command Line, User-defined, Top
  1038. X@chapter Built-in Variables
  1039. X@cindex built-in variables
  1040. X
  1041. XMost @code{awk} variables are available for you to use for your own
  1042. Xpurposes; they never change except when your program assigns them, and
  1043. Xnever affect anything except when your program examines them.
  1044. X
  1045. XA few variables have special built-in meanings.  Some of them @code{awk}
  1046. Xexamines automatically, so that they enable you to tell @code{awk} how
  1047. Xto do certain things.  Others are set automatically by @code{awk}, so
  1048. Xthat they carry information from the internal workings of @code{awk} to
  1049. Xyour program.
  1050. X
  1051. XThis chapter documents all the built-in variables of @code{gawk}.  Most
  1052. Xof them are also documented in the chapters where their areas of
  1053. Xactivity are described.
  1054. X
  1055. X@menu
  1056. X* User-modified::  Built-in variables that you change to control @code{awk}.
  1057. X
  1058. X* Auto-set::       Built-in variables where @code{awk} gives you information.
  1059. X@end menu
  1060. X
  1061. X@node User-modified, Auto-set, Built-in Variables, Built-in Variables
  1062. X@section Built-in Variables That Control @code{awk}
  1063. X@cindex built-in variables, user modifiable
  1064. X
  1065. XThis is a list of the variables which you can change to control how
  1066. X@code{awk} does certain things.
  1067. X
  1068. X@table @code
  1069. X@c it's unadvisable to have multiple index entries for the same name
  1070. X@c since in Info there is no way to distinguish the two.
  1071. X@c @vindex FS
  1072. X@item FS
  1073. X@code{FS} is the input field separator (@pxref{Field Separators}).
  1074. XThe value is a single-character string or a multi-character regular
  1075. Xexpression that matches the separations between fields in an input
  1076. Xrecord.
  1077. X
  1078. XThe default value is @w{@code{" "}}, a string consisting of a single
  1079. Xspace.  As a special exception, this value actually means that any
  1080. Xsequence of spaces and tabs is a single separator.  It also causes
  1081. Xspaces and tabs at the beginning or end of a line to be ignored.
  1082. X
  1083. XYou can set the value of @code{FS} on the command line using the
  1084. X@samp{-F} option:
  1085. X
  1086. X@example
  1087. Xawk -F, '@var{program}' @var{input-files}
  1088. X@end example
  1089. X
  1090. X@item IGNORECASE
  1091. X@c @vindex IGNORECASE
  1092. XIf @code{IGNORECASE} is nonzero, then @emph{all} regular expression
  1093. Xmatching is done in a case-independent fashion.  In particular, regexp
  1094. Xmatching with @samp{~} and @samp{!~}, and the @code{gsub} @code{index},
  1095. X@code{match}, @code{split} and @code{sub} functions all ignore case when
  1096. Xdoing their particular regexp operations.  @strong{Note:} since field
  1097. Xsplitting with the value of the @code{FS} variable is also a regular
  1098. Xexpression operation, that too is done with case ignored.
  1099. X@xref{Case-sensitivity}.
  1100. X
  1101. XIf @code{gawk} is in compatibility mode (@pxref{Command Line}), then
  1102. X@code{IGNORECASE} has no special meaning, and regexp operations are
  1103. Xalways case-sensitive.@refill
  1104. X
  1105. X@item OFMT
  1106. X@c @vindex OFMT
  1107. XThis string is used by @code{awk} to control conversion of numbers to
  1108. Xstrings (@pxref{Conversion}).  It works by being passed, in effect, as
  1109. Xthe first argument to the @code{sprintf} function.  Its default value
  1110. Xis @code{"%.6g"}.@refill
  1111. X
  1112. X@item OFS
  1113. X@c @vindex OFS
  1114. XThis is the output field separator (@pxref{Output Separators}).  It is
  1115. Xoutput between the fields output by a @code{print} statement.  Its
  1116. Xdefault value is @w{@code{" "}}, a string consisting of a single space.
  1117. X
  1118. X@item ORS
  1119. X@c @vindex ORS
  1120. XThis is the output record separator.  It is output at the end of every
  1121. X@code{print} statement.  Its default value is a string containing a
  1122. Xsingle newline character, which could be written as @code{"\n"}.
  1123. X(@xref{Output Separators}).@refill
  1124. X
  1125. X@item RS
  1126. X@c @vindex RS
  1127. XThis is @code{awk}'s record separator.  Its default value is a string
  1128. Xcontaining a single newline character, which means that an input record
  1129. Xconsists of a single line of text.  (@xref{Records}.)@refill
  1130. X
  1131. X@item SUBSEP
  1132. X@c @vindex SUBSEP
  1133. X@code{SUBSEP} is a subscript separator.  It has the default value of
  1134. X@code{"\034"}, and is used to separate the parts of the name of a
  1135. Xmulti-dimensional array.  Thus, if you access @code{foo[12,3]}, it
  1136. Xreally accesses @code{foo["12\0343"]}.  (@xref{Multi-dimensional}).@refill
  1137. X@end table
  1138. X
  1139. X@node Auto-set, , User-modified, Built-in Variables
  1140. X@section Built-in Variables That Convey Information to You
  1141. X
  1142. XThis is a list of the variables that are set automatically by @code{awk}
  1143. Xon certain occasions so as to provide information for your program.
  1144. X
  1145. X@table @code
  1146. X@item ARGC
  1147. X@itemx ARGV
  1148. X@c @vindex ARGC
  1149. X@c @vindex ARGV
  1150. XThe command-line arguments available to @code{awk} are stored in an
  1151. Xarray called @code{ARGV}.  @code{ARGC} is the number of command-line
  1152. Xarguments present.  @code{ARGV} is indexed from zero to @w{@code{ARGC - 1}}.
  1153. X@xref{Command Line}.  For example:
  1154. X
  1155. X@example
  1156. Xawk '@{ print ARGV[$1] @}' inventory-shipped BBS-list
  1157. X@end example
  1158. X
  1159. X@noindent
  1160. XIn this example, @code{ARGV[0]} contains @code{"awk"}, @code{ARGV[1]}
  1161. Xcontains @code{"inventory-shipped"}, and @code{ARGV[2]} contains
  1162. X@code{"BBS-list"}.  The value of @code{ARGC} is 3, one more than the
  1163. Xindex of the last element in @code{ARGV} since the elements are numbered
  1164. Xfrom zero.@refill
  1165. X
  1166. XNotice that the @code{awk} program is not entered in @code{ARGV}.  The
  1167. Xother special command line options, with their arguments, are also not
  1168. Xentered.  But variable assignments on the command line @emph{are}
  1169. Xtreated as arguments, and do show up in the @code{ARGV} array.
  1170. X
  1171. XYour program can alter @code{ARGC} and the elements of @code{ARGV}.
  1172. XEach time @code{awk} reaches the end of an input file, it uses the next
  1173. Xelement of @code{ARGV} as the name of the next input file.  By storing a
  1174. Xdifferent string there, your program can change which files are read.
  1175. XYou can use @code{"-"} to represent the standard input.  By storing
  1176. Xadditional elements and incrementing @code{ARGC} you can cause
  1177. Xadditional files to be read.
  1178. X
  1179. XIf you decrease the value of @code{ARGC}, that eliminates input files
  1180. Xfrom the end of the list.  By recording the old value of @code{ARGC}
  1181. Xelsewhere, your program can treat the eliminated arguments as
  1182. Xsomething other than file names.
  1183. X
  1184. XTo eliminate a file from the middle of the list, store the null string
  1185. X(@code{""}) into @code{ARGV} in place of the file's name.  As a
  1186. Xspecial feature, @code{awk} ignores file names that have been
  1187. Xreplaced with the null string.
  1188. X
  1189. X@item ENVIRON
  1190. X@vindex ENVIRON
  1191. XThis is an array that contains the values of the environment.  The array
  1192. Xindices are the environment variable names; the values are the values of
  1193. Xthe particular environment variables.  For example,
  1194. X@code{ENVIRON["HOME"]} might be @file{/u/close}.  Changing this array
  1195. Xdoes not affect the environment passed on to any programs that
  1196. X@code{awk} may spawn via redirection or the @code{system} function.
  1197. X(In a future version of @code{gawk}, it may do so.)
  1198. X
  1199. XSome operating systems may not have environment variables.
  1200. XOn such systems, the array @code{ENVIRON} is empty.
  1201. X
  1202. X@item FILENAME
  1203. X@c @vindex FILENAME
  1204. XThis is the name of the file that @code{awk} is currently reading.
  1205. XIf @code{awk} is reading from the standard input (in other words,
  1206. Xthere are no files listed on the command line),
  1207. X@code{FILENAME} is set to @code{"-"}.
  1208. X@code{FILENAME} is changed each time a new file is read (@pxref{Reading
  1209. XFiles}).@refill
  1210. X
  1211. X@item FNR
  1212. X@c @vindex FNR
  1213. X@code{FNR} is the current record number in the current file.  @code{FNR} is
  1214. Xincremented each time a new record is read (@pxref{Getline}).
  1215. XIt is reinitialized to 0 each time a new input file is started.
  1216. X
  1217. X@item NF
  1218. X@c @vindex NF
  1219. X@code{NF} is the number of fields in the current input record.
  1220. X@code{NF} is set each time a new record is read, when a new field is
  1221. Xcreated, or when @code{$0} changes (@pxref{Fields}).@refill
  1222. X
  1223. X@item NR
  1224. X@c @vindex NR
  1225. XThis is the number of input records @code{awk} has processed since
  1226. Xthe beginning of the program's execution.  (@pxref{Records}).
  1227. X@code{NR} is set each time a new record is read.@refill
  1228. X
  1229. X@item RLENGTH
  1230. X@c @vindex RLENGTH
  1231. X@code{RLENGTH} is the length of the substring matched by the
  1232. X@code{match} function (@pxref{String Functions}).  @code{RLENGTH} is set
  1233. Xby invoking the @code{match} function.  Its value is the length of the
  1234. Xmatched string, or @minus{}1 if no match was found.@refill
  1235. X
  1236. X@item RSTART
  1237. X@c @vindex RSTART
  1238. X@code{RSTART} is the start-index of the substring matched by the
  1239. X@code{match} function (@pxref{String Functions}).  @code{RSTART} is set
  1240. Xby invoking the @code{match} function.  Its value is the position of the
  1241. Xstring where the matched substring starts, or 0 if no match was
  1242. Xfound.@refill
  1243. X@end table
  1244. X
  1245. X@node Command Line, Language History, Built-in Variables, Top
  1246. X@c node-name, next, previous, up
  1247. X@chapter Invocation of @code{awk}
  1248. X@cindex command line
  1249. X@cindex invocation of @code{gawk}
  1250. X@cindex arguments, command line
  1251. X@cindex options, command line
  1252. X
  1253. XThere are two ways to run @code{awk}: with an explicit program, or with
  1254. Xone or more program files.  Here are templates for both of them; items
  1255. Xenclosed in @samp{@r{[}@dots{}@r{]}} in these templates are optional.
  1256. X
  1257. X@example
  1258. Xawk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{}
  1259. Xawk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{}
  1260. X@end example
  1261. X
  1262. X@menu
  1263. X* Options::             Command line options and their meanings.
  1264. X* Other Arguments::     Input file names and variable assignments.
  1265. X* AWKPATH Variable::    Searching directories for @code{awk} programs.
  1266. X@end menu
  1267. X
  1268. X@node Options, Other Arguments, Command Line, Command Line
  1269. X@section Command Line Options
  1270. X
  1271. XOptions begin with a minus sign, and consist of a single character.
  1272. XThe options and their meanings are as follows:
  1273. X
  1274. X@table @code
  1275. X@item -F@var{fs}
  1276. XSets the @code{FS} variable to @var{fs} (@pxref{Field Separators}).
  1277. X
  1278. X@item -f @var{source-file}
  1279. XIndicates that the @code{awk} program is to be found in @var{source-file}
  1280. Xinstead of in the first non-option argument.
  1281. X
  1282. X@item -v @var{var}=@var{val}
  1283. X@cindex @samp{-v} option
  1284. XSets the variable @var{var} to the value @var{val} @emph{before}
  1285. Xexecution of the program begins.  Such variable values are available
  1286. Xinside the @code{BEGIN} rule (see below for a fuller explanation).
  1287. X
  1288. XThe @samp{-v} option only has room to set one variable, but you can use
  1289. Xit more than once, setting another variable each time, like this:
  1290. X@samp{@w{-v foo=1} @w{-v bar=2}}.
  1291. X
  1292. X@item -a
  1293. XSpecifies use of traditional @code{awk} syntax for regular expressions.
  1294. XThis means that @samp{\} can be used to quote any regular expression
  1295. Xoperators inside of square brackets, just as it can be outside of them.
  1296. XThis mode is currently the default; the @samp{-a} option is useful in
  1297. Xshell scripts so that they will not break if the default is changed.
  1298. X@xref{Regexp Operators}.
  1299. X
  1300. X@item -e
  1301. XSpecifies use of @code{egrep} syntax for regular expressions.  This
  1302. Xmeans that @samp{\} does not serve as a quoting character inside of
  1303. Xsquare brackets; ideosyncratic techniques are needed to include various
  1304. Xspecial characters within them.  This mode may become the default at
  1305. Xsome time in the future.  @xref{Regexp Operators}.
  1306. X
  1307. X@item -c
  1308. X@cindex @samp{-c} option
  1309. XSpecifies @dfn{compatibility mode}, in which the GNU extensions in
  1310. X@code{gawk} are disabled, so that @code{gawk} behaves just like Unix
  1311. X@code{awk}.  These extensions are noted below, where their usage is
  1312. Xexplained.  @xref{Compatibility Mode}.
  1313. X
  1314. X@item -V
  1315. X@cindex @samp{-V} option
  1316. XPrints version information for this particular copy of @code{gawk}.
  1317. XThis is so you can determine if your copy of @code{gawk} is up to date
  1318. Xwith respect to whatever the Free Software Foundation is currently
  1319. Xdistributing.  This option may disappear in a future version of @code{gawk}.
  1320. X
  1321. X@item -C
  1322. X@cindex @samp{-C} option
  1323. XPrints the short version of the General Public License.
  1324. XThis option may disappear in a future version of @code{gawk}.
  1325. X
  1326. X@item --
  1327. XSignals the end of the command line options.  The following arguments
  1328. Xare not treated as options even if they begin with @samp{-}.  This
  1329. Xinterpretation of @samp{--} follows the POSIX argument parsing
  1330. Xconventions.
  1331. X
  1332. XThis is useful if you have file names that start with @samp{-},
  1333. Xor in shell scripts, if you have file names that will be specified
  1334. Xby the user and that might start with @samp{-}.
  1335. X@end table
  1336. X
  1337. XAny other options are flagged as invalid with a warning message, but
  1338. Xare otherwise ignored.
  1339. X
  1340. XIn compatibility mode, as a special case, if the value of @var{fs} supplied
  1341. Xto the @samp{-F} option is @samp{t}, then @code{FS} is set to the tab
  1342. Xcharacter (@code{"\t"}).  Also, the @samp{-C} and @samp{-V} options
  1343. Xare not recognized.@refill
  1344. X
  1345. XIf the @samp{-f} option is @emph{not} used, then the first non-option
  1346. Xcommand line argument is expected to be the program text.
  1347. X
  1348. XThe @samp{-f} option may be used more than once on the command line.
  1349. XThen @code{awk} reads its program source from all of the named files, as
  1350. Xif they had been concatenated together into one big file.  This is
  1351. Xuseful for creating libraries of @code{awk} functions.  Useful functions
  1352. Xcan be written once, and then retrieved from a standard place, instead
  1353. Xof having to be included into each individual program.  You can still
  1354. Xtype in a program at the terminal and use library functions, by specifying
  1355. X@samp{-f /dev/tty}.  @code{awk} will read a file from the terminal
  1356. Xto use as part of the @code{awk} program.  After typing your program,
  1357. Xtype @kbd{Control-d} (the end-of-file character) to terminate it.
  1358. X
  1359. X@node Other Arguments, AWKPATH Variable, Options, Command Line
  1360. X@section Other Command Line Arguments
  1361. X
  1362. XAny additional arguments on the command line are normally treated as
  1363. Xinput files to be processed in the order specified.  However, an
  1364. Xargument that has the form @code{@var{var}=@var{value}}, means to assign
  1365. Xthe value @var{value} to the variable @var{var}---it does not specify a
  1366. Xfile at all.
  1367. X
  1368. X@vindex ARGV
  1369. XAll these arguments are made available to your @code{awk} program in the
  1370. X@code{ARGV} array (@pxref{Built-in Variables}).  Command line options
  1371. Xand the program text (if present) are omitted from the @code{ARGV}
  1372. Xarray.  All other arguments, including variable assignments, are
  1373. Xincluded.
  1374. X
  1375. XThe distinction between file name arguments and variable-assignment
  1376. Xarguments is made when @code{awk} is about to open the next input file.
  1377. XAt that point in execution, it checks the ``file name'' to see whether
  1378. Xit is really a variable assignment; if so, @code{awk} sets the variable
  1379. Xinstead of reading a file.
  1380. X
  1381. XTherefore, the variables actually receive the specified values after all
  1382. Xpreviously specified files have been read.  In particular, the values of
  1383. Xvariables assigned in this fashion are @emph{not} available inside a
  1384. X@code{BEGIN} rule (@pxref{BEGIN/END}), since such rules are run before
  1385. X@code{awk} begins scanning the argument list.@refill
  1386. X
  1387. XIn some earlier implementations of @code{awk}, when a variable assignment
  1388. Xoccurred before any file names, the assignment would happen @emph{before}
  1389. END_OF_FILE
  1390.   if test 49666 -ne `wc -c <'./gawk.texinfo.05'`; then
  1391.     echo shar: \"'./gawk.texinfo.05'\" unpacked with wrong size!
  1392.   fi
  1393.   # end of './gawk.texinfo.05'
  1394. fi
  1395. if test -f './patchlevel.h' -a "${1}" != "-c" ; then 
  1396.   echo shar: Will not clobber existing file \"'./patchlevel.h'\"
  1397. else
  1398.   echo shar: Extracting \"'./patchlevel.h'\" \(21 characters\)
  1399.   sed "s/^X//" >'./patchlevel.h' <<'END_OF_FILE'
  1400. X#define PATCHLEVEL    1
  1401. END_OF_FILE
  1402.   if test 21 -ne `wc -c <'./patchlevel.h'`; then
  1403.     echo shar: \"'./patchlevel.h'\" unpacked with wrong size!
  1404.   fi
  1405.   # end of './patchlevel.h'
  1406. fi
  1407. if test -f './pc.d/popen.c' -a "${1}" != "-c" ; then 
  1408.   echo shar: Will not clobber existing file \"'./pc.d/popen.c'\"
  1409. else
  1410.   echo shar: Extracting \"'./pc.d/popen.c'\" \(2046 characters\)
  1411.   sed "s/^X//" >'./pc.d/popen.c' <<'END_OF_FILE'
  1412. X#include <stdio.h>
  1413. X#include "popen.h"
  1414. X#include <io.h>
  1415. X#include <string.h>
  1416. X#include <process.h>
  1417. X
  1418. Xstatic char template[] = "piXXXXXX";
  1419. Xtypedef enum { unopened = 0, reading, writing } pipemode;
  1420. Xstatic
  1421. Xstruct {
  1422. X    char *command;
  1423. X    char *name;
  1424. X    pipemode pmode;
  1425. X} pipes[_NFILE];
  1426. X
  1427. XFILE *
  1428. Xpopen( char *command, char *mode ) {
  1429. X    FILE *current;
  1430. X    char *name;
  1431. X    int cur;
  1432. X    pipemode curmode;
  1433. X    /*
  1434. X    ** decide on mode.
  1435. X    */
  1436. X    if(strcmp(mode,"r") == 0)
  1437. X        curmode = reading;
  1438. X    else if(strcmp(mode,"w") == 0)
  1439. X        curmode = writing;
  1440. X    else
  1441. X        return NULL;
  1442. X    /*
  1443. X    ** get a name to use.
  1444. X    */
  1445. X    if((name = tempnam(".","pip"))==NULL)
  1446. X        return NULL;
  1447. X    /*
  1448. X    ** If we're reading, just call system to get a file filled with
  1449. X    ** output.
  1450. X    */
  1451. X    if(curmode == reading) {
  1452. X        char cmd[256];
  1453. X        sprintf(cmd,"%s > %s",command,name);
  1454. X        system(cmd);
  1455. X        if((current = fopen(name,"r")) == NULL)
  1456. X            return NULL;
  1457. X    } else {
  1458. X        if((current = fopen(name,"w")) == NULL)
  1459. X            return NULL;
  1460. X    }
  1461. X    cur = fileno(current);
  1462. X    pipes[cur].name = name;
  1463. X    pipes[cur].pmode = curmode;
  1464. X    pipes[cur].command = strdup(command);
  1465. X    return current;
  1466. X}
  1467. X
  1468. Xint
  1469. Xpclose( FILE * current) {
  1470. X    int cur = fileno(current),rval;
  1471. X    /*
  1472. X    ** check for an open file.
  1473. X    */
  1474. X    if(pipes[cur].pmode == unopened)
  1475. X        return -1;
  1476. X    if(pipes[cur].pmode == reading) {
  1477. X        /*
  1478. X        ** input pipes are just files we're done with.
  1479. X        */
  1480. X        rval = fclose(current);
  1481. X        unlink(pipes[cur].name);
  1482. X    } else {
  1483. X        /*
  1484. X        ** output pipes are temporary files we have
  1485. X        ** to cram down the throats of programs.
  1486. X        */
  1487. X        char command[256];
  1488. X        fclose(current);
  1489. X        sprintf(command,"%s < %s",pipes[cur].command,pipes[cur].name);
  1490. X        rval = system(command);
  1491. X        unlink(pipes[cur].name);
  1492. X    }
  1493. X    /*
  1494. X    ** clean up current pipe.
  1495. X    */
  1496. X    pipes[cur].pmode = unopened;
  1497. X    free(pipes[cur].name);
  1498. X    free(pipes[cur].command);
  1499. X    return rval;
  1500. X}
  1501. X
  1502. END_OF_FILE
  1503.   if test 2046 -ne `wc -c <'./pc.d/popen.c'`; then
  1504.     echo shar: \"'./pc.d/popen.c'\" unpacked with wrong size!
  1505.   fi
  1506.   # end of './pc.d/popen.c'
  1507. fi
  1508. echo shar: End of archive 4 \(of 16\).
  1509. cp /dev/null ark4isdone
  1510. MISSING=""
  1511. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ; do
  1512.     if test ! -f ark${I}isdone ; then
  1513.     MISSING="${MISSING} ${I}"
  1514.     fi
  1515. done
  1516. if test "${MISSING}" = "" ; then
  1517.     echo You have unpacked all 16 archives.
  1518.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1519. else
  1520.     echo You still must unpack the following archives:
  1521.     echo "        " ${MISSING}
  1522. fi
  1523. exit 0
  1524. exit 0 # Just in case...
  1525.